from django.shortcuts import render
from .models import User
# Create your views here.
from django.http import HttpResponse
import json
from django.core import serializers # Django提供的序列化queryset到JSON字符串转换

def xhr(res):
    return render(res, 'xhr.html')

def get_xhr(res):
    return render(res, 'get-xhr.html')

def get_xhr_server(res):
    print("123456")
    if res.GET.get('uname'):
        name = res.GET['uname']
        print(name)
        return HttpResponse('欢迎 '+ name)
    return HttpResponse("这是一个Ajax请求!")

def getuser_list(res):
    if res.method == 'GET':
        booksc = User.objects.all()
        # 如果需要安装条件查找在大于,小于,大于等于,小于等于符号不能用>,<,>=,<=符号, 详情转 Django教程day04.md
        # 需要替换Django对等的变量,即 查询谓词, __gt 是大于的意思
        # books = models.Book.objects.filter(price__gt=50)
        
        # locals() 方法自动传递 booksc 变量
        return render(res, 'list.html', locals())

def getuser_listsc(res):
    booksc = User.objects.all()
    # ms = ''
    # for i in booksc:
    #     ms += f'{i.id}, {i.uname}, {i.pwd}, {i.nickname}|'
    #     print(ms)
    # msd = ms[:-1]
    
    # 以上方法传参不推荐, 使用JSON传参更加高效
    ms = []
    for i in booksc:
        msd = {}
        msd['id'] = i.id
        msd['pwd'] = i.pwd
        msd['uname'] = i.uname
        msd['nickname'] = i.nickname
        ms.append(msd)
        # print(ms)
    # msd = ms[:-1]
    # python的json, sort_keys为有序, 对字符串顺序有要求则打开, separators为格式化字符,默认有空格,格式化之后没有了
    ms = json.dumps(ms, separators=(',', ':'))
    print(ms)
    
    # Django提供的序列化queryset到JSON字符串转换,以提供更加详细的数据
    # msd = serializers.serialize('json', queryset=booksc)
    return HttpResponse(ms, content_type='application/json')
    

#%% 利用Ajax来实现注册
def register(res):
    """返回注册页面"""
    return render(res, 'register.html')

def checkuname(res):
    """实现注册功能"""
    # 1, 获取Ajax传过来的用户名
    uname = res.GET.get('uname')
    
    # 2, 对比数据库用户名是否存在
    users = User.objects.filter(uname = uname).all()
    if users:
        return HttpResponse(0)
    elif uname == '' or len(uname) < 6:
        return HttpResponse(2)
    return HttpResponse(1)

#%% ajax实现post传输
def make_post(res):
    if res.method == 'GET':
        return render(res, 'make_post.html')
    elif res.method == 'POST':
        uname = res.POST.get('uname')
        pwd = res.POST.get('pwd')
        pwd1 = res.POST.get('pwd1')
        unames = res.POST.get('unames')
        if not uname:
            return HttpResponse(3)
        elif pwd != pwd1 or pwd == '' or pwd1 == '' or len(pwd) <= 5:
            return HttpResponse(0)
        elif not unames:
            return HttpResponse(2)
        try:
            User.objects.create(uname=uname, pwd=pwd1, nickname=unames)
            return HttpResponse('1')
        except Exception as e:
            return HttpResponse('4')
    else:
        raise
    
    